#include <Arduino.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include "ArduinoJson.h"

// 记得解压ArduinoJson文件夹

// JOSN是一种轻量级的数据交换格式，遵循一下规则：
// 1.并列的数据之间用逗号(,)分隔
// 2.映射用冒号(:)表示
// 3.并列数据的集合(数组)用方括号([])表示
// 4.映射的集合(对象)用大括号({})表示

//	WiFi的初始化和连接
void WiFi_Connect()
{
	WiFi.begin("123456", "776654321");
	while (WiFi.status() != WL_CONNECTED)
	{ //这里是阻塞程序，直到连接成功
		delay(300);
		Serial.print(".");
	}
}

void setup()
{

	Serial.begin(115200); // open the serial port at 115200 bps;
	delay(100);
	Serial.print("Connecting.. ");
	WiFi_Connect();
	Serial.println("WiFi connected");
	Serial.println("IP address: ");
	Serial.println(WiFi.localIP());
}

String dataUrl = "https://api.seniverse.com/v3/weather/now.json?key=SeiP2ViJVtkngR1s5&location=luoyang&language=zh-Hans&unit=c";

DynamicJsonDocument doc(1024);

//	获取粉丝数
void get_internet_data()
{
	HTTPClient http;
	http.begin(dataUrl); //HTTP begin
	int httpCode = http.GET();

	if (httpCode > 0)
	{
		// httpCode will be negative on error
		Serial.printf("HTTP Get Code: %d\r\n", httpCode);

		if (httpCode == HTTP_CODE_OK) // 收到正确的内容
		{
			//返回的数据字符串
			String resBuff = http.getString();
			Serial.println(resBuff);

			//	使用ArduinoJson_6.x版本，具体请移步：https://github.com/bblanchon/ArduinoJson
			deserializeJson(doc, resBuff); //开始使用Json解析
			JsonObject results_0 = doc["results"][0];

			JsonObject results_0_location = results_0["location"];
			const char* results_0_location_id = results_0_location["id"]; // "WQPUYY7S4GV2"
			const char* results_0_location_name = results_0_location["name"]; // "洛阳"
			const char* results_0_location_country = results_0_location["country"]; // "CN"
			const char* results_0_location_path = results_0_location["path"]; // "洛阳,洛阳,河南,中国"
			const char* results_0_location_timezone = results_0_location["timezone"]; // "Asia/Shanghai"
			const char* results_0_location_timezone_offset = results_0_location["timezone_offset"]; // "+08:00"

			JsonObject results_0_now = results_0["now"];
			const char* results_0_now_text = results_0_now["text"]; // "阴"
			const char* results_0_now_code = results_0_now["code"]; // "9"
			const char* results_0_now_temperature = results_0_now["temperature"]; // "3"

			const char* results_0_last_update = results_0["last_update"]; // "2022-02-19T19:19:03+08:00"
			Serial.println(results_0_now_code);
			Serial.println(results_0_location_name);
			Serial.println(results_0_location_path);

		}
	}
	else
	{
		Serial.printf("HTTP Get Error: %s\n", http.errorToString(httpCode).c_str());
	}

	http.end();
}

void loop()
{
	get_internet_data();
	delay(3000);
}
